// ==UserScript==
// @name           Cincinnati Library Searches!
// @namespace      http://userscripts.org/users/useridnumber
// @description    allow Cincinnati Library catalog searches by shortcut
// @include        http://catalog.cincinnatilibrary.org/*
// ==/UserScript==

/*
History:

2009.05.24 - Click further through successful hold requests
*/

// TODO: implement the selectDue function below, so that it can go through and select the proper items to be renewed.

// TODO: create openSearch xml files for the following searches (http://dev.chromium.org/tab-to-search) window.external.AddSearchProvider('file.xml')



// Search for music:
// http://catalog.cincinnatilibrary.org/?music=%s

// Search for author:
// http://catalog.cincinnatilibrary.org/?author=%s

// search for phrase:
// http://catalog.cincinnatilibrary.org/?word=%s

// search for DVD title:
// http://catalog.cincinnatilibrary.org/?title=%s&DVD

// search for CD title:
// http://catalog.cincinnatilibrary.org/?title=%s&CD

//document.addEventListener('load',
//  function(e){


function xmlencode(string) {
    return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
        .replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
}

function selectDue(days)
{
  if(typeof(days)!="number"){
    var name=days.target.id;
    var match=/_(\d+)$/.exec(name);
    days=parseInt(match[1]);
  }
  var sender = document.getElementById('select_due_' + days);
  var checked = true;
  if(sender) {
    checked = sender.checked;
    if(days > 0) {
      document.getElementById('select_due_0').checked = checked;
      if(days > 7) {
        document.getElementById('select_due_7').checked = checked;
      }
    }
  }
  var date = new Date();
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  date.setMilliseconds(0);
  date = new Date(date.valueOf() + ((days + 1) * 24 * 3600000));

  var renewitems = document.getElementById('renewcharge');
  var rows = renewitems.rows;
  for(var i=0; rows.length > i; i++)
  {
     try {
       var dueAt = Date.parse(rows[i].cells[3].innerText);
       var cb = rows[i].getElementsByTagName('input')[0];
       if(date > dueAt) {
         cb.checked = checked;
       }
     } catch(Exception) { }
  }
}

function selectAllVolumes() {
  var i=1;
  var elem = document.getElementById('call_selection' + i);
  while(elem != null) {
    elem.checked = !elem.checked;
    i++;
    elem = document.getElementById('call_selection' + i);
  }
}

chrome.extension.sendRequest({show:true}, function(response) {});

function initHoldOptions() {
  var holdform = document.getElementById("holdform");
  var volumeSelection = document.getElementById('call_selection1');
  if(holdform && volumeSelection) {
    var parent = volumeSelection.parentElement
    if(parent != null) {
      var button = document.createElement('input');
      button.type = 'button';
      button.value = 'Select all volumes';
      button.onclick=selectAllVolumes;
      parent.insertAdjacentElement('beforeBegin',button);
    }
  }
}

function initRenewOptions()
{
  var renewsubmit = document.getElementById('select_all_charges');
  if(renewsubmit)
  {
    // if there is a renew selected items button, add some options to select all items due today, and all due within the next week, and 2 weeks.
    var tr = renewsubmit.parentElement;
    while(!tr.tagName.match(/tr/i)) {
      tr = tr.parentElement;
    }
    var button = document.createElement('input');
    button.type = 'checkbox';
    button.id = 'select_due_0';
    button.onclick=selectDue;
    var label = document.createElement('label');
    label.innerText = 'All due today';
    label.setAttribute('for',button.id);
    label.className = "accountstyle";
    var newRow = document.createElement('tr');
    var newElement = document.createElement('td');
    newElement.colSpan = 7;
    newElement.appendChild(button);
    newElement.appendChild(label);
    newRow.appendChild(newElement);
    tr.insertAdjacentElement('afterEnd',newRow);
    tr = newRow;

    button = document.createElement('input');
    button.type = 'checkbox';
    button.id = 'select_due_7';
    button.onclick=selectDue;
    label = document.createElement('label');
    label.innerText = 'All due within 1 week';
    label.setAttribute('for',button.id);
    label.className = "accountstyle";
    newRow = document.createElement('tr');
    newElement = document.createElement('td');
    newElement.colSpan = 7;
    newElement.appendChild(button);
    newElement.appendChild(label);
    newRow.appendChild(newElement);
    tr.insertAdjacentElement('afterEnd',newRow);
    tr = newRow;

    button = document.createElement('input');
    button.type = 'checkbox';
    button.id = 'select_due_14';
    button.onclick=selectDue;
    label = document.createElement('label');
    label.innerText = 'All due within 2 weeks';
    label.setAttribute('for',button.id);
    label.className = "accountstyle";
    newRow = document.createElement('tr');
    newElement = document.createElement('td');
    newElement.colSpan = 7;
    newElement.appendChild(button);
    newElement.appendChild(label);
    newRow.appendChild(newElement);
    tr.insertAdjacentElement('afterEnd',newRow);
    tr = newRow;

//    button = document.createElement('input');
//    button.type = 'submit';
//    button.value = 'Renew Selected Items';
//    button.class = 'searchbutton';
//    parent.insertAdjacentElement('afterEnd',button);
    //renewoptions.insertAdjacentElement('afterEnd',div);
  }
  //main();
}

//window.addEventListener('load', initRenewOptions, false);
initRenewOptions();
initHoldOptions();

function someChecked(myForm) {
  if (myForm != null)
  {
    checkboxes = myForm.length;
    for (count = 0; count < checkboxes; count++)
      if (myForm[count].type == 'checkbox' && myForm[count].onclick == null && myForm[count].checked == true)
        return true;
  }
  return false;
}

function checkUserPass() {
  var userid = document.getElementById('user_id');
  var password = document.getElementById('password');
  var pickupLibrary = document.getElementById('pickup_library');
  
  if(location.search) {
    var tryrenew = location.search.match(/[?&]tryrenew/i);
    var needToGoToAccountPage = tryrenew && location.pathname.match(/\/0\/0\/49$/);
    if(!needToGoToAccountPage) {
      var selectToday = document.getElementById('select_due_0');
      if(selectToday) {
        selectToday.checked = true;
        selectDue(0);
        var renewItems = document.getElementById('renewitems');
        if(someChecked(renewItems)) {
          renewItems.submit();
        } else {
          //chrome.windows.getCurrent(function(window) {
            chrome.extension.sendRequest({closeWindow:true});
          //});
        }
      }
    }
    var rootbar = document.getElementsByClassName('rootbar');
    for(i in rootbar) {
      var a = rootbar[i];
      if(a.href) {
        a.href += location.search;
        if(needToGoToAccountPage && a.innerText.match(/My Account/)) {
          location = a.href;
        }
      }
    }
  }
    
  chrome.extension.sendRequest({getLibrary:true}, function(response) {
    var library = response;
    
    if(!library) {
      library = 'Symmes Township';
    }
    if(userid && userid.value != '' && password && password.value != '') {
      var accessform = document.getElementsByName('accessform')[0];
      if(accessform)
      {
      // if there's a user name and password form that won't login, submit it, unless it is requesting a password change.
      // Also don't submit if we don't have a saved user name and password...
        if(document.getElementById('new_password1'))
          return;
        accessform.action += location.search;
        accessform.submit();
        return;
      }
    }
    var holdform = document.getElementsByName('holdform')[0];
    if(holdform)
    {
    //TODO: add an options page to select the default library to use
    // if the hold form is being displayed, select "Symmes Township" as the branch at which to pick up the hold, and submit the form if there aren't more than one volume.
      var selLibrary = document.getElementById('pickup_library');
      selLibrary.value=library;
      if(selLibrary.value != library) {
        var regex = new RegExp(library,'i');
        for(var i=0; i<selLibrary.options.length; i++)
        {
          if(selLibrary.options[i].text.match(regex))
          {
            selLibrary.selectedIndex = i;
            break;
          }
        }
      }
      var submitHold = !location.href.match(/\/1000$/);
      var volumeSelection = document.getElementById('call_selection1');
      if(submitHold && !volumeSelection)
        holdform.submit();
      return;
    }
  });
}
setTimeout(checkUserPass, 100);

function main() {
window.external.AddSearchProvider('http://cincylibraryjs.googlecode.com/files/lword.xml');
window.external.AddSearchProvider('http://cincylibraryjs.googlecode.com/files/lmusic.xml');
window.external.AddSearchProvider('http://cincylibraryjs.googlecode.com/files/lauthor.xml');
window.external.AddSearchProvider('http://cincylibraryjs.googlecode.com/files/ldvd.xml');

    var regexPattern = /(?:\^\w[0-9-]{4,}\^)([^\^]*?)(?:(v.)0*([\d+]))?\^(?:[^\^\r\n]*\^([^\^\r\n]*)\^([^\^\r\n]*))?/;
    var tryhold = (null !== location.search.match(/tryhold/i));
    var tryrenew = (null !== location.search.match(/tryrenew/i));
    var title = "";
    var mediatype = "";
    var holdresult = document.getElementById('holdResult');
    var detailsinfo = document.getElementById('details_info');
    
    if(tryrenew) {
      alert("Try Renew?");
    } else if(tryhold && detailsinfo)
    {
    // if the url is an item URL and ends with ?tryhold, try to put a hold on the item, by clicking the "Place Hold" link.
      var links = detailsinfo.getElementsByClassName("placehold_link");
      for(i in links)
      {
        if(links[i].innerText.match(/Place Hold/))
        {
          window.location = links[i].href;
          return;
        }
      }
    }
  }
